const Service = require('egg').Service;
const url =
  'http://api.ipnebula.com/?country=$$&sep=1&num=1&format=2&protocol=http';
const request = require('superagent');
const wjw = require('../../wjw/utils');
const dayjs = require('dayjs');
require('superagent-proxy')(request);
// process.binding('http_parser').HTTPParser = require('http-parser-js').HTTPParser;
class HomeService extends Service {
  async submit(data) {
    const { query_string, sendUrl, cookie } =
      await this.ctx.service.submit.getQuery(
        'https://www.wjx.cn/vm/h6b487E.aspx'
      );
    data.url = sendUrl;
    data.query_string = Object.keys(query_string).reduce((q, cur) => {
      q += `${cur}=${query_string[cur]}&`;
      return q;
    }, '&');
    data.request_headers.cookie = cookie;
    const proxy = {
      host: null,
      port: null,
    };
    // 1. 根据region去获取ip
    const result = await this.ctx.curl(url.replace('$$', data.region), {
      dataType: 'json',
    });
    if (result.status === 200) {
      const ipRes = result.data;
      if (ipRes.code === 0) {
        proxy.host = ipRes.data[0][0];
        proxy.port = ipRes.data[0][1];
      }
    }
    if (proxy.host && proxy.port) {
      const proxyUrl = `http://${proxy.host}:${proxy.port}`;
      // 2. 发送请求
      const res = await new Promise((resolve, reject) => {
        request
          .send(data.submit_data)
          .proxy(proxyUrl)
          .end((e, res) => {
            if (e) {
              reject(e);
            }
            resolve(res);
          });
      });
      return res;
    }
  }
  async submit_v2(data) {
    this.ctx.logger.info(data);
    this.ctx.logger.info(data.submit_data);
    this.ctx.logger.info(data.request_headers.content_type);
    let res = null;
    const proxy_url = data.proxy_url;
    const userAndPwd = proxy_url.match(/\/\/(.*)\@/)[1];
    if (userAndPwd) {
      const area = userAndPwd.match(/\-(.*)\:/)[1];
      // data.proxy_url = data.proxy_url.replace(userAndPwd, `cuveecui_area-${area}:yydj8888`);
      data.proxy_url = `http://customer-94ca1a-country-${area.toUpperCase()}:73300586@proxy.ipipgo.com:31212`;
    }
    this.logger.info('proxy_url', data.proxy_url);
    // data.proxy_url = 'http://customer-94ca1a-country-PT:73300586@proxy.ipipgo.com:31212';
    try {
      res = await new Promise((resolve, reject) => {
        request
          .post(data.url)
          .send(data.submit_data)
          .proxy(data.proxy_url)
          .set(data.request_headers)
          .timeout(10000)
          .end((e, res) => {
            this.logger.info('success')
            if (e) {
              this.ctx.logger.error('request success but response error', e);
              reject(e);
            }
            resolve(res);
          });
      });
    } catch (e) {
      this.ctx.logger.error('catch error: ', e);
    }
    if (res && res.status === 200) {
      this.ctx.logger.info(res.text);
      return res.text;
    } else {
      this.ctx.logger.error(res);
    }
  }
  async getWjxParams(originSendUrl, region) {
    originSendUrl = originSendUrl || 'https://www.wjx.cn/vm/h6b487E.aspx';
    // 1. 根据region去获取ip
    const proxy = {
      host: null,
      port: null,
    };
    const result = await this.ctx.curl(url.replace('$$', region || 'us'), {
      dataType: 'json',
    });
    if (result.status === 200) {
      const ipRes = result.data;
      console.log(ipRes);
      if (ipRes.code === 0) {
        proxy.host = ipRes.data[0][0];
        proxy.port = ipRes.data[0][1];
      }
    }
    const { query_string, sendUrl, cookie } =
      await this.ctx.service.submit.getQuery(originSendUrl);
    return {
      submit_data: {
        submitdata: '1$1}2$1}3$1!1,2!1,3!1',
      },
      request_headers: {
        'User-Agent':
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        Host: 'www.wjx.cn',
        Referer: 'https://www.wjx.cn/vm/h6b487E.aspx',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        cookie,
      },
      url:
        sendUrl +
        Object.keys(query_string).reduce((q, cur) => {
          q += `${cur}=${query_string[cur]}&`;
          return q;
        }, '&'),
      proxy_url: `http://${proxy.host}:${proxy.port}`,
    };
  }
  async getWjwparams(originSendUrl, region) {
    originSendUrl = originSendUrl || 'https://www.wjx.cn/vm/h6b487E.aspx';
    // 1. 根据region去获取ip
    const proxy = {
      host: null,
      port: null,
    };
    const result = await this.ctx.curl(url.replace('$$', region || 'us'), {
      dataType: 'json',
    });
    if (result.status === 200) {
      const ipRes = result.data;
      if (ipRes.code === 0 && ipRes.data && ipRes.data.length) {
        proxy.host = ipRes.data[0][0];
        proxy.port = ipRes.data[0][1];
      } else {
        return ipRes.msg;
      }
    }
    const timestr = dayjs().add(-120, 'second').format('YYYY-MM-DD HH:mm:ss');
    const timestamp = dayjs().valueOf();
    return {
      ...wjw(timestr, timestamp, originSendUrl),
      proxy_url: `http://${proxy.host}:${proxy.port}`,
    };
  }
  // }
}

module.exports = HomeService;
